import { Provide, Inject } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { UserProfileProfileEntity } from '../entity/profile';
import { UserProfileHistoryEntity } from '../entity/history';

/**
 * 用户档案信息
 */
@Provide()
export class UserProfileProfileService extends BaseService {
  @InjectEntityModel(UserProfileProfileEntity)
  userProfileProfileEntity: Repository<UserProfileProfileEntity>;

  @InjectEntityModel(UserProfileHistoryEntity)
  userProfileHistoryEntity: Repository<UserProfileHistoryEntity>;

  @Inject()
  ctx;

  /**
   * 通过用户ID获取档案信息
   */
  async getByUserId(userId: number) {
    return await this.userProfileProfileEntity.findOne({
      where: { userId }
    });
  }

  /**
   * 添加或更新用户档案信息
   */
  async addOrUpdateByUserId(param: any) {
    // 检查是否存在该用户的档案
    const exists = await this.userProfileProfileEntity.findOne({
      where: { userId: param.userId }
    });

    if (exists) {
      // 如果存在则更新
      // 记录修改历史
      const changes = [];

      // 比较每个字段的变化
      for (const key in param) {
        if (JSON.stringify(exists[key]) !== JSON.stringify(param[key])) {
          changes.push({
            profileId: exists.id,
            modifiedField: key,
            oldValue: JSON.stringify(exists[key]),
            newValue: JSON.stringify(param[key]),
            operationTime: new Date(),
            operatorId: this.ctx.admin?.userId,
            operationIp: this.ctx.ip,
            operationDevice: this.ctx.headers['user-agent']
          });
        }
      }

      // 保存修改历史
      if (changes.length > 0) {
        await this.userProfileHistoryEntity.save(changes);
      }

      // 更新档案
      await this.userProfileProfileEntity.update(exists.id, {
        ...param,
        updateTime: new Date()
      });
      return await this.userProfileProfileEntity.findOne({
        where: { id: exists.id }
      });
    } else {
      // 如果不存在则新增
      const entity = this.userProfileProfileEntity.create({
        ...param,
        createTime: new Date(),
        updateTime: new Date()
      });
      return await this.userProfileProfileEntity.save(entity);
    }
  }
}
